import axios from 'axios'
import { Message } from 'element-ui'

import {config} from '@/api/api'

// 创建一个错误
function errorCreate(msg) {
  const error = new Error(msg)
  errorLog(error)
  throw error
}

// 记录和显示错误
function errorLog(response) {
  let url = response.request.responseURL

  // 打印到控制台
  if (process.env.NODE_ENV === 'development') {
    console.log('>>>>>> Error >>>>>>')
    console.log(response)
  }
  
  // 显示提示
  Message({
    message: config.getErrorMsg(response.data, url),
    type: 'error',
    showClose: true,
    duration: 3000,
  })
}

// 创建一个 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API,
  timeout: 5000, // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    // 发送失败
    console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    let url = response.request.responseURL

    // 响应码不是正常的2xx
    if(!/^2\d{2}/g.test(response?.status) || config.isErrorRes(response?.data, url)){
      errorLog(response)
      return Promise.reject(response?.data);
    }
    return response?.data
  },
  (error) => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误'
          break
        case 401:
          break
        case 402:
          break
        case 403:
          error.message = `身份已失效，请重新登录`
          window.location.href = '../sys-nt/login.html'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
      }
    }
    errorLog(error.response)
    return Promise.reject(error)
  }
)

export default service
